/*
 * NCSSParserWrapper.java
 * 
 * Copyright (c) 2007
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.dcarew.javancss.metrics;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javancss.JavaParser;
import javancss.ParseException;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;

/**
 * 
 * 
 * @author Devon Carew
 */
public class NCSSParserWrapper
{

	public NCSSParserWrapper()
	{

	}

	public NCSSMetrics parse(IResource resource)
	{
		return parse(resource, new NCSSMetrics());
	}

	public NCSSMetrics parse(IResource resource, NCSSMetrics metrics)
	{
		if (resource.getLocation() == null)
			return null;

		IPath path = resource.getLocation();

		File file = new File(path.toOSString());

		if (!file.exists() || !file.canRead())
			return null;

		try
		{
			metrics.incFileCount();
			metrics.incByteCount(file.length());
			
			InputStream in = new BufferedInputStream(new FileInputStream(file), 10240);
			
			JavaParser ncssParser = new JavaParser(in);
			
			ncssParser.CompilationUnit();
			
			metrics.incPackageCount(ncssParser.getPackage());
			metrics.incNCSSCount(ncssParser.getNcss());
			metrics.incLOCCount(ncssParser.getLOC());
			metrics.incJavaDocCount(ncssParser.getJvdc());
			metrics.incCycCount(ncssParser.getFunction());
			
			safeClose(in);
			
			return metrics;
		}
		catch (FileNotFoundException fnfe)
		{
			fnfe.printStackTrace();

			return null;
		}
		catch (ParseException pe)
		{
			return null;
		}
	}

	private void safeClose(InputStream in)
	{
		try
		{
			if (in != null)
				in.close();
		}
		catch (IOException ioe)
		{
			
		}
	}

}
